<?php
namespace App\Helpers;

use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Response;

/**
 * 网页版响应
 * @package App\Helpers
 */
trait WebResponse
{
    /**
     * 返回状态码
     * @var int
     */
    protected $resStatusCode = FoundationResponse::HTTP_OK;
    protected $resJumpTime = 1000;
    protected $resTemplateFile = 'admin.shared.showmsg';

    /**
     * @return mixed
     */
    public function getStatusCode()
    {
        return $this->resStatusCode;
    }

    /**
     * @param $statusCode
     * @return $this
     */
    public function setStatusCode($statusCode)
    {
        $this->resStatusCode = $statusCode;
        return $this;
    }
    /**
     * 信息提示页.
     *
     * @param string $type success|error|info|warning|404|500
     * @param string $msg
     * @param string $redirectUrl
     * @param array  $otherData
     */
    public function showMsg($type = 'success', $msg = '',$otherData = [], $url = '')
    {
        $data = [];
        $data['status'] = $type;
        $bgClass = 'bg-primary';
        switch ($type) {
            case 'success':
                $data['title'] = '操作成功';
                $bgClass = 'bg-success';
                break;
            case 'error':
                $data['title'] = '操作失败';
                $bgClass = 'bg-danger';
                break;
            case 'info':
                $data['title'] = '消息提示';
                $bgClass = 'bg-info';
                break;
            case 'warning':
                $data['title'] = '错误警告';
                $bgClass = 'bg-warning';
                break;
            default:
                $data['title']  = '提示';
        }
        $data['message']     = $msg;
        $data['data']  = $otherData;
        //跳转地址
        if ($url){
            if (URL::isValidUrl($url)){
                $data['url'] = $url;
            }else{
                $data['url'] = route($url);
            }
        }else{
            $data['url'] = URL::previous();
        }
        $requestType = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
        if ($requestType == 'xmlhttprequest') {
            return Response::json($data);
        } else {
            $httpStatus = $this->resStatusCode;
            $data['bgClass'] = $bgClass;
            $data['jumpTime'] = $this->resJumpTime;
            return Response::view($this->resTemplateFile, $data, $httpStatus);
        }
    }

}